﻿
using System;
using System.Linq;
using System.Linq.Expressions;
using SmallShop.Core;
using SmallShop.Dal;
using SmallShop.Frame;

namespace SmallShop.Bll
{
    public class BaseBiz<T> where T : BaseModel, new()
    {
        protected BaseBiz()
        {
            DataAccess = new DefaultDataAccess();
        }

        protected IDataAccess DataAccess;

        public virtual IQueryable<T> Query()
        {
            return DataAccess.Query<T>();
        }

        public virtual IQueryable<T> Query(Expression<Func<T, bool>> predicate)
        {
            return Query().Where(predicate);
        }


        #region protected
        protected virtual ResultModel Add(T model, bool autoSave = true)
        {
            model.Id = IdWorker.NextId();
            DataAccess.Add(model);
            SaveChange(autoSave);
            return new ResultModel { Data = model.Id };
        }

        protected virtual ResultModel Update(T model, bool autoSave )
        {
            DataAccess.Update(model);
            SaveChange(autoSave);
            return new ResultModel();
        }

        protected virtual ResultModel Delete(T model, bool autoSave )
        {
            DataAccess.Delete(model);
            SaveChange(autoSave);
            return new ResultModel();
        }

        protected virtual ResultModel Delete(long id, bool autoSave )
        {
            var mode = Query().FirstOrDefault(it => it.Id == id);
            if (mode == null)
            {
                return new ResultModel();
            }
            return Delete(mode);
        }



        #endregion

        #region Product 

        public virtual ResultModel Add(T model)
        {
            return Add(model, true);
        }

        public virtual ResultModel Update(T model)
        {
            return Update(model, true);
        }

        public virtual ResultModel Delete(T model)
        {
            return Delete(model, true);
        }

        public virtual ResultModel Delete(long id)
        {
            return Delete(id, true);
        }

        #endregion

        /// <summary>
        /// 保存更改
        /// </summary>
        private void SaveChange(bool autoSave )
        {
            if (autoSave)
            {
                DataAccess.SaveChange();
            }
        }

        /// <summary>
        /// 保存更改
        /// </summary>
        public void SaveChange()
        {
            SaveChange(true);
        }
    }
}
